package com.cars.ui.servlets;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cars.dto.Product;
import com.cars.service.InventoryService;

/**
 * Servlet implementation class AdvanceSearchServlet
 */
@WebServlet("/search")
public class AdvanceSearchServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	InventoryService inventoryService = null;

	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		super.init();
		inventoryService = new InventoryService();
	}

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AdvanceSearchServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String lowerAmount = request.getParameter("lowerAmount").trim();
		String upperAmount = request.getParameter("upperAmount").trim();
		RequestDispatcher dispatcher = request
				.getRequestDispatcher("search.jsp");

		if (lowerAmount.equalsIgnoreCase("")) {
			lowerAmount = "0";
		}

		if (upperAmount.equalsIgnoreCase("")
				|| Double.valueOf(upperAmount) <= 0.0) {

			request.setAttribute("errorMessageStatus", "show");
			request.setAttribute("errorMessage",
					"Invalid Maximum Dollar value , Please try again.");

			dispatcher.forward(request, response);
		} else {
			request.setAttribute("errorMessageStatus", "hide");
			request.setAttribute("errorMessage", null);
			List<Product> productsList = inventoryService
					.getProductsByPriceRange(Double.valueOf(lowerAmount),
							Double.valueOf(upperAmount));
			request.setAttribute("productsList", productsList);
			dispatcher.forward(request, response);

		}

	}

}
